<?php
	if(!isset($_SESSION)){
		session_start();
	}
	
	// Clear previous messages.
	if(isset($_SESSION['error'])) session_unregister('error');
	if(isset($_SESSION['success'])) session_unregister('success');
	if(isset($_SESSION['flag'])) session_unregister('flag');

	// Get values from the form.
	$subCategoryName = $_POST['subCategoryName'];
	$subCategoryDescription = $_POST['subCategoryDescription'];
	$categoryId = $_POST['categoryId'];
	
	// Check for validation.
	if($categoryId == 0 || $subCategoryName == ""){
		$_SESSION['error'] = "Please complete the mandatory fields".$categoryId;		
	}else{
		include("../dbconnection.php");
		if($result = mysql_query("SELECT * FROM sub_categories WHERE subCategoryName='$subCategoryName'")){
			if(mysql_num_rows($result) > 0){
				$row = mysql_fetch_assoc($result);
				$_SESSION['error'] = "Sub category name ".$row['subCategoryName']." is already exisist.";
			}else{
				if(mysql_query("INSERT INTO sub_categories (subcategoryName, subCategoryDescription, categoryId) VALUES ('$categoryName','$categoryDescription','$categoryId')")){
					$_SESSION['success'] = "sub category added successfully.";
				}else{
					$_SESSION['error'] = "Error occured! 1".mysql_error();
				}
			}
		}else{
			$_SESSION['error'] = "Error occured! 2".mysql_error();
		}
	}
	$_SESSION['flag']="sub";
	$_SESSION['page'] = "addCategories.php";
	header('Location: ../../');
?>